package com.tran.app.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tran.app.MyApp
import com.tran.app.dao.AppDatabase
import com.tran.app.data.Course
import com.tran.app.data.CourseSelectionCancellation
import com.tran.app.data.UserInfo
import com.tran.app.utils.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class DropScreenVM:ViewModel(){

    fun agree(selectcancel: Askinfo) {
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                AppDatabase.getInstance(MyApp.instance).courseSelectionCancellationDao().
                deleteCourseSelectionAndCancellation(selectcancel.selectcancel.courseSelectionId)
                _uiData.value = _uiData.value.copy(
                    list = _uiData.value.list.filterNot { it.selectcancel.id == selectcancel.selectcancel.id }
                )
            }
            show("处理成功")
        }
    }

    fun refuse(selectcancel: Askinfo) {
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                AppDatabase.getInstance(MyApp.instance).courseSelectionCancellationDao().delete(selectcancel.selectcancel)
                _uiData.value = _uiData.value.copy(
                    list = _uiData.value.list.filterNot { it.selectcancel.id == selectcancel.selectcancel.id }
                )
            }
            show("处理成功")
        }
    }

    data class Askinfo(val user: UserInfo, val course: Course,val selectcancel:CourseSelectionCancellation)
    data class UiState(val list: List<Askinfo>)
    val initialUiState = UiState(emptyList())
    private val _uiData = MutableStateFlow(initialUiState)
    val uiData: StateFlow<UiState> = _uiData.asStateFlow()
    init {
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                val cancellations = AppDatabase.getInstance(MyApp.instance).courseSelectionCancellationDao()
                    .getAllCancellationsByTeacherAccount(MyApp.user)
                val askInfoList = cancellations.map { cancellation ->
                    val userInfo = AppDatabase.getInstance(MyApp.instance).userInfoDao().getUserById(cancellation.studentId)
                    val course = AppDatabase.getInstance(MyApp.instance).courseDao().getCoursesById (cancellation.courseId)
                    Askinfo(userInfo!!, course, cancellation)
                }
                _uiData.update {
                    it.copy(list = askInfoList)
                }
            }
        }
    }
}